<!--
 * @Author: 汪军 624473119@qq.com
 * @Date: 2023-10-10 18:15:53
 * @LastEditors: 汪军 624473119@qq.com
 * @LastEditTime: 2023-10-19 11:00:55
 * @FilePath: \ekee-web\src\views\end\easy-link\EasyLink.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template lang="pug">
.easy-out-manage-add
  .title.flex.justify-center.bold.mb4 {{ rowId ? "编辑" : "新增" }}
  .form-content.flex
    .require.w100
      el-form(
        ref="formRef",
        :model="form",
        label-position="left",
        label-width="100px",
        status-icon
      )
        el-row(:gutter="40")
          el-col(:span="9")
            el-form-item(label="易出名称：", prop="name")
              el-input(v-model="form.name", placeholder="请输入", maxlength="20",clearable)
          el-col(:span="9")
            el-form-item(label="行业类目：", prop="category_id")
              el-select(
                v-model="form.category_id",
                placeholder="请选择",
                clearable,
                @change="categoryChange"
              )
                el-option(
                  v-for="item in categoryList",
                  :key="item.id",
                  :label="item.name",
                  :value="item.id"
                )

        el-form-item(label="图片：", prop="image")
          el-upload.avatar-uploader(
            action="https://api.ekee.com.cn/api/common/upload",
            :show-file-list="false",
            :on-success="handleAvatarSuccess"
          )
            <img v-if="form.image" :src="form.image" class="avatar" />
            el-icon.avatar-uploader-icon(v-else) <Plus />
        el-form-item(label="详情：", prop="address")
          .toolbar
            Toolbar(
              :editor="editorRef",
              :defaultConfig="toolbarConfig",
              :mode="mode",
              style="border-bottom: 1px solid #dcdfe6"
            )
            Editor(
              style="width: 850px; min-height: 200px",
              v-model="valueHtml",
              :defaultConfig="editorConfig",
              :mode="mode",
              @onCreated="handleCreated",
              @onChange="handleChange",
              @onDestroyed="handleDestroyed",
              @onFocus="handleFocus",
              @onBlur="handleBlur",
              @customAlert="customAlert",
              @customPaste="customPaste"
            )
          //- el-input(v-model="form.address" type="textarea" :autosize="{minRows: 4, maxRows: 4}" placeholder="请输入" clearable)
        el-button.add-btn.mb4(type="primary", size="large", @click="onAdd") 添加规格
        el-form-item(label="规格列表：", prop="tableData")
          el-table(
            :data="form.tableData",
            :header-cell-style="tableHeaderStyle",
            :cell-style="tableCellStyle",
            empty-text="暂无数据，请先添加规格",
            border,
            style="width: 100%"
          )
            el-table-column(prop="name", label="规格名称")
            el-table-column(prop="image", label="封面图")
              template(v-slot="scope")
                img.img-size(:src="scope.row.image")
            el-table-column(prop="price", label="单价")
            el-table-column(prop="stock", label="库存")
            el-table-column(prop="min_sales_quantity", label="最小起换量")
            el-table-column(fixed="right", label="操作", width="170")
              template(v-slot="scope", #default)
                el-button(
                  link,
                  type="primary",
                  size="small",
                  @click="onEdit(scope.row, scope.$index)"
                ) 编辑
                el-button.overdue(
                  link,
                  type="primary",
                  size="small",
                  @click="onDelete(scope.row)"
                ) 删除
  .flex.justify-center.mt4.mb4
    el-button.btn(
      type="primary",
      size="large",
      plain,
      round,
      @click="onCancel(formRef)"
    ) 取消
    el-button.btn(
      type="primary",
      size="large",
      round,
      @click="onConfirm(formRef)"
    ) 确认
  //- 添加规格
  el-dialog(
    v-model="addSpecificationVisible",
    width="622",
    align-center,
    :show-close="false",
    :destroy-on-close="true",
    center
  )
    AddSpecification(
      :recordId="recordId",
      :goods_id="goods_id",
      :editGoodsSaveInfo="editGoodsSaveInfo",
      @cancel="addSpecificationVisible = false",
      @confirm="onAddSpecificationConfirm"
    )
</template>

<script setup>
import { ref, onBeforeUnmount, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Category, Area, editorUpload } from "@/api/common";
import AddSpecification from "@/views/end/easy-out-manage/components/AddSpecification.vue";
import "@wangeditor/editor/dist/css/style.css";
import { GoodsSave, GoodsDelete, GoodsHxInfo } from "@/api/outmanagement";
import { getUserInfo, removeUserInfo } from "@/service";
const props = defineProps({
  rowId: "",
});
onMounted(() => {
  const userInfo = getUserInfo();
  editorToken.value = userInfo.token;
  console.log("token", userInfo.token);
  editTable.value = props.rowIds;
  //编辑的时候传过来 goos_id
  goods_id.value = props.rowId;
  getCategory();
  if (props.rowId) {
    getGoodsHxInfo(props.rowId);
  }
});

const goods_id = ref("");
const editorToken = ref("");
//如果是编辑
const editTable = ref("");
const editTableindex = ref(null);
//获取行业类目
const getCategory = () => {
  Category().then((res) => {
    categoryList.value = res.data;
  });
};
const categoryList = ref([]);
const categoryChange = (val) => {
  console.log("val", val);
  form.value.category_id = val;
};

//编辑回显
const getGoodsHxInfo = (rowId) => {
  GoodsHxInfo({ id: rowId }).then((res) => {
    if (res.code == 1) {
      form.value.id = res.data.id;
      form.value.name = res.data.name;
      form.value.category_id = res.data.category_id;
      form.value.image = res.data.image;
      valueHtml.value = res.data.description;
      (form.value.goods_spec_ids = res.data.goods_spec_ids), //规格ID集，多个用逗号隔开，编辑时不用传
        (form.value.tableData = res.data.spec_list);
    }
  });
};

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';
//   }, 1500);
// });
const toolbarConfig = {
  toolbarKeys: [
    "bold",
    "underline",
    "italic",
    "color",
    "bgColor",
    "fontSize",
    "bold",
    "indent",
    "delIndent",
    "justifyLeft",
    "justifyRight",
    "justifyCenter",
    "justifyJustify",
    "lineHeight",
    "bulletedList",
    "numberedList",
    "uploadImage",
  ],
};
// 编辑器配置
const editorConfig = {
  MENU_CONF: {
    // uploadImage: {
    //   fieldName: "file",
    //   server: "https://api.ekee.com.cn/api/common/upload",
    //   // 单个文件的最大体积限制，默认为 2M
    //   maxFileSize: 2 * 1024 * 1024, // 1M
    //   // 最多可上传几个文件，默认为 100
    //   // maxNumberOfFiles: 10,
    //   // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
    //   allowedFileTypes: [],
    //   // 上传进度的回调函数，可以用来显示进度条
    //   onProgress(progress) {
    //     // progress 是 0-100 的数字
    //     console.log("progress", progress);
    //   },
    //   // // 单个文件上传成功之后
    //   onSuccess(file, res) {
    //     console.log(`${file.name} 上传成功`, res);
    //   },
    //   // 单个文件上传失败
    //   onFailed(file, res) {
    //     console.log(`${file.name} 上传失败`, res);
    //   },
    //   // 上传错误，或者触发 timeout 超时
    //   onError(file, err, res) {
    //     console.log(`${file.name} 上传出错`, err, res);
    //   },
    //   // 插入图片到富文本编辑器回显
    //   customInsert(res, insertFn) {
    //     console.log();
    //     // res 即服务端的返回结果
    //     getPhotoUrl(res.data[0]).then((res) => {
    //       console.log("回显", res);
    //       // const url = res.data;
    //       // const alt = "";
    //       // const href = res.data;
    //       // 从 res 中找到 url alt href ，然后插入图片
    //       // insertFn(url, alt, href);
    //     });
    //   },
    // },
  },
  placeholder: "请输入内容...",
  withCredentials: true, //定义该属性为ture表示允许跨域访问
  autofocus: false,
  scroll: false,
  maxLength: 800,
  minLength: 200,
};

// 上传图片
editorConfig.MENU_CONF["uploadImage"] = {
  // form-data fieldName ，默认值 'wangeditor-uploaded-image'
  // fieldName: "file",
  // server: "https://api.ekee.com.cn/api/common/editor_upload",
  // // 单个文件的最大体积限制，默认为 2M
  maxFileSize: 5 * 1024 * 1024, // 1M
  // // 最多可上传几个文件，默认为 100
  // maxNumberOfFiles: 10,
  // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
  // allowedFileTypes: [],
  // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
  // meta: {
  //   token: editorToken.value,
  // },

  // 将 meta 拼接到 url 参数中，默认 false
  // metaWithUrl: false,
  // // 自定义增加 http  header
  // headers: {
  //   token: editorToken.value,
  // },

  // server: baseURL + '/upload',
  //
  // 	          meta: {
  // 	            type: 1,
  // 	          },
  // 	          headers: { ...this.headers },

  // 跨域是否传递 cookie ，默认为 false
  withCredentials: true,
  // // 超时时间，默认为 10 秒
  timeout: 3 * 1000, // 5 秒
  // 自定义上传

  onSuccess(file, res) {
    // JS 语法
    console.log(`${file.name} 上传成功`, res);
  },

  // 单个文件上传失败
  onFailed(file, res) {
    // JS 语法
    console.log(`${file.name} 上传失败`, res);
    console.log("editorToken.value", editorToken.value);
  },

  // 上传错误，或者触发 timeout 超时
  onError(file, err, res) {
    // JS 语法
    console.log(`${file.name} 上传出错`, err, res);
  },

  // customInsert(res, insertFn) {
  //   // JS 语法
  //   // res 即服务端的返回结果

  //   // 从 res 中找到 url alt href ，然后插入图片
  //   insertFn(url, alt, href);
  // },
  async customUpload(file, insertFn) {
    let imgData = new FormData();
    imgData.append("file", file);
    // JS 语法
    // 自己实现上传，并得到图片 url alt href
    await editorUpload(imgData).then((res) => {
      console.log("测试", res);

      if (res.errno == 0) {
        const { url, alt, href } = res.data;
        insertFn(url, alt, href);
      }
    });
  },
};
// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
// 编辑器回调函数
const handleCreated = (editor) => {
  console.log("created", editor);
  editorRef.value = editor; // 记录 editor 实例，重要！
  // nextTick(() => {
  //   editorRef.value = editor; // 一定要用 Object.seal() ，否则会报错
  // });
};
const handleChange = (editor) => {
  console.log("change:", editor.getHtml());
};
const handleDestroyed = (editor) => {
  console.log("destroyed", editor);
};
const handleFocus = (editor) => {
  console.log("focus", editor);
};
const handleBlur = (editor) => {
  console.log("blur", editor);
};

const formRef = ref();
const rules = ref({
  name: [{ required: true, message: "请输入易入名称", trigger: "blur" }],
  category_id: [
    {
      required: true,
      message: "请选择行业类目",
      trigger: "change",
    },
  ],
  image: [
    {
      required: true,
      message: "请选择图片",
      trigger: "change",
    },
  ],
  // address: [
  //   {
  //     required: true,
  //     message: "请选择收货区域",
  //     trigger: "change",
  //   },
  // ],
});
const form = ref({
  id: "",
  name: "",
  category_id: "",
  image: "",
  description: "", //描述
  goods_spec_ids: "", //规格ID集，多个用逗号隔开，编辑时不用传
  tableData: [],
});
const tableHeaderStyle = ref({
  backgroundColor: "#E5E6EB",
  color: "#000000",
  textAlign: "center",
});
const tableCellStyle = ref({
  textAlign: "center",
});
const recordId = ref("");
const editGoodsSaveInfo = ref({});
const addSpecificationVisible = ref(false);

const emits = defineEmits(["cancel", "confirm"]);

const handleAvatarSuccess = (response, uploadFile) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log("上传", response, uploadFile);
  form.value.image = response.data.url;
};

// 取消
const onCancel = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  emits("cancel");
};

// 确认
const onConfirm = (formEl) => {
  if (!formEl) return;
  if (form.value.tableData.length == 0) {
    ElMessage({ message: "请添加规格,再易出商品", type: "warning" });
    return;
  }
  formEl.validate((valid, fields) => {
    if (valid) {
      form.value.description = valueHtml.value;
      emits("confirm", form.value);
      console.log("submit!", form.value, valueHtml.value);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 新增&&编辑&&删除规格
const onAdd = (row) => {
  // if(goods_id.value){
  //   goods_id.value=goods_id.value;
  //   addSpecificationVisible.value = true;
  //   return;
  // }
  recordId.value = "";
  addSpecificationVisible.value = true;
};
const onEdit = (row, index) => {
  console.log("编辑", row.id);
  console.log("rowe", row);
  editTableindex.value = index;
  //这里面穿的是规格id

  recordId.value = row.id;
  editGoodsSaveInfo.value = row;
  addSpecificationVisible.value = true;
};
const onDelete = (row) => {
  let deleteId = row.id;

  GoodsDelete({ id: row.id }).then((res) => {
    if (res.code == 1) {
      ElMessage({ message: res.msg, type: "success" });
      form.value.tableData.forEach((item, index) => {
        if (item.id == deleteId) {
          form.value.tableData.splice(index, 1);
        }
      });
    }
  });
};
//编辑回显

const goodsInfo = ref([]);
const setGoogsInfo = ref([]);
const onAddSpecificationConfirm = (value) => {
  //如果是编辑
  // if(){

  // }
  // form.value.tableData=[]
  if (editTableindex.value != null && value.id) {
    console.log("11", 1111);
    form.value.tableData[editTableindex.value] = value;
  } else {
    form.value.tableData.push(value);
  }
  console.log("sfsdk", value);
  console.log("sf", value.id);

  addSpecificationVisible.value = false;

  console.log("form.value.tableData", form.value.tableData);

  let goods_spec_ids = [];
  form.value.tableData.forEach((item, index) => {
    goods_spec_ids.push(item.id);
  });
  form.value.goods_spec_ids = goods_spec_ids.join(",");

  // console.log("哎课程授课", goodsInfo.value);
};
</script>

<style lang="stylus" scoped>
.easy-out-manage-add {
  .title {
    font-size: 24px;
  }

  .form-content {
    padding: 0px 66px;

    .require {
      padding: 16px 12px;
      border: 1px solid #E6E6E6;
      height: 400px;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .no-require {
      margin-left: 32px;
      padding: 16px 12px;
      border: 1px solid #E6E6E6;
    }
  }

  .input-width {
    width: 245px;
  }

  .add-btn {
    margin-left: 100px;
    width: 114px;
  }

  .btn {
    width: 178px;
  }

  .overdue {
    color: #E84026;
  }

  .refund {
    color: #2487E8;
  }

  .no-quota {
    margin-top: 200px;
  }

  // 上传图片相关
  .avatar-uploader .el-upload {
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 58px;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: #dcdfe6;
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 152px;
    height: 100px;
    text-align: center;
    border: 1px dashed #dcdfe6;
  }

  .avatar-uploader .avatar {
    width: 152px;
    height: 100px;
    display: block;
  }

  .toolbar {
    border: 1px solid #dcdfe6;
  }

  .img-size {
    width: 100px;
    height: 58px;
    border-radius: 10px 10px 10px 10px;
  }
}
</style>
